package vip.xiaonuo.biz.modular.nccAi.provider;

import com.alibaba.fastjson.JSONObject;
import com.coze.openapi.client.exception.CozeApiException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.api.BizFileManagerApi;
import vip.xiaonuo.biz.api.BizNccAiApi;
import vip.xiaonuo.biz.modular.nccAi.entity.BizAiNcc;
import vip.xiaonuo.biz.modular.nccAi.service.BizAiNccService;
import vip.xiaonuo.biz.modular.nccAi.util.CozeClient;

import java.util.List;

/**
 * ClassName:BizNccAiApiProvider
 * Description:
 *
 * @Author:薛守立
 * @CreateTime:2025/4/24 14:36
 */
@Slf4j
@Service
public class BizNccAiApiProvider implements BizNccAiApi {

    private static String workFlowId = "7481464889277054985";

    @Resource
    BizAiNccService bizAiNccService;


    @Override
    public void checkCozeWorkFlowStatus() {
        List<BizAiNcc> list = bizAiNccService.queryCozeStatus();
        log.info("当前待提交ncc单据数量为：{}",list.size());
        if(!list.isEmpty()){
            CozeClient cozeClient = new CozeClient();
            list.forEach(item->{
                // 查询coze状态
                try {
                    String res = cozeClient.checkWorkFlow(workFlowId, item.getExecuteId());
                    if (!res.equals("running")){
                        // 封装参数，执行ncc接口
                        log.info("coze请求的结果参数：{}",res);
                        // json 字符串转义
                        JSONObject jsonObject = JSONObject.parseObject(res);
                        Object json = jsonObject.get("Output");
                        JSONObject jsonRes = JSONObject.parseObject(json.toString());
                        Object cozeRes = jsonRes.get("data");
                        bizAiNccService.updateCozeStatus(item.getId(), cozeRes.toString());
                        item.setExtJson(cozeRes.toString());
                        bizAiNccService.createNccPay(item);
                    }
                }catch (CozeApiException e){
                    log.info("错误信息：{}", e.toString());
                }


            });
        }
    }
}
